//
//  WeiBoManager.swift
//  MyLottery
//
//  Created by wujunjie on 2018/7/24.
//  Copyright © 2018年 wujunjie. All rights reserved.
//

import UIKit
//MARK:单例
class WeiBoManager {
    static let manager = WeiBoManager()
}

//MARK :关于微博的一些SDK的公开方法
extension WeiBoManager{
    //MARK: 手机是否安装了微博 app
    class func  isWeiBoAppInstalled()->Bool{
        return WeiboSDK.isWeiboAppInstalled()
    }
    /// 微博登录
    func weiboLogin(){
        let wbAuthorizeRequest =  WBAuthorizeRequest()
        wbAuthorizeRequest.scope = "all"
        wbAuthorizeRequest.redirectURI = "https://baidu.com"
        wbAuthorizeRequest.userInfo = ["SSO_From":"SendMessageToWeiboViewController","Other_Info_1":111];
        wbAuthorizeRequest.shouldShowWebViewForAuthIfCannotSSO = false
        WeiboSDK .send(wbAuthorizeRequest)
    }
    ///微博登录的通知
    func weiboDidLoginNotification(notification:Notification){
        let userInfo = notification.userInfo
        let accessToken = userInfo!["accessToken"]
        let userId = userInfo!["userId"]
        getWeiboUserInfoWithAccessToken(accessToken: accessToken as! String, userId: userId as! String)
    }
    ///从微博那里获取信息
    func getWeiboUserInfoWithAccessToken(accessToken:String,userId:String){
        let url = String("https://api.weibo.com/2/users/show.json?access_token=\(accessToken)&uid=\(userId)")
        let sonQueue = DispatchQueue.global()
        sonQueue.async {
            let zoneUrl = NSURL(string: url)
            do{
                let zoneStr = try String(contentsOf: zoneUrl! as URL, encoding: String.Encoding.utf8)
                let data = zoneStr.data(using: String.Encoding.utf8)
                let mainQueue = DispatchQueue.main
                mainQueue.async {
                    do{
                        if data != nil{
                            let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.init(rawValue: 0))
                            print(dic)

                        }
                    }catch{
                        print(error)
                    }
                }
            }catch{
                print(error)
            }
        }
    }
}



